package com.study.project.config;

import com.study.project.realm.MyRealm;
import org.apache.shiro.spring.web.config.DefaultShiroFilterChainDefinition;
import org.apache.shiro.util.ThreadContext;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;

import javax.annotation.Resource;
import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {

    @Resource
    private MyRealm myRealm;

    @Bean
    public DefaultWebSecurityManager defaultWebSecurityManager() {
        //1.创建返回对象
        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
        //2.创建加密对象，设置相关属性
        //HashedCredentialsMatcher matcher = new HashedCredentialsMatcher();
        //matcher.setHashAlgorithmName("md5");
        //matcher.setHashIterations(3);

        //3.将加密对象存储到myRealm中
        //myRealm.setCredentialsMatcher(matcher);

        //4.将自定义Realm存入defaultWebSecurityManager中
        defaultWebSecurityManager.setRealm(myRealm);
        ThreadContext.bind(defaultWebSecurityManager);
        //返回defaultWebSecurityManager对象
        return defaultWebSecurityManager;
    }

    @Bean
    public DefaultShiroFilterChainDefinition shiroFilterChainDefinition() {
        DefaultShiroFilterChainDefinition chainDefinition = new DefaultShiroFilterChainDefinition();
        //设置可访问资源路径
        chainDefinition.addPathDefinition("/login", "anon");
        //放行Swagger2页面，需要放行这些
        Map<String, String> filterMap = new LinkedHashMap<>();
        filterMap.put("/swagger-ui.html", "anon");
        filterMap.put("/swagger/**", "anon");
        filterMap.put("/doc.html", "anon");
        filterMap.put("/webjars/**", "anon");
        filterMap.put("/v2/**", "anon");
        filterMap.put("/swagger-resources/**", "anon");
        filterMap.put("/static/**", "anon");
        chainDefinition.addPathDefinitions(filterMap);

        //设置不可访问资源路径
        chainDefinition.addPathDefinition("/**", "authc");
        return chainDefinition;
    }

    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/doc.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
        registry.addResourceHandler("/swagger-ui/**").addResourceLocations("classpath:/META-INF/resources/webjars/springfox-swagger-ui/").resourceChain(false);
    }
}
